package com.yuchting.dinneronline.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DateBox;
import com.yuchting.dinneronline.client.common.CommonDialog;
import com.yuchting.dinneronline.client.common.Order;
import com.yuchting.dinneronline.client.common.YesNoHandler;
import com.yuchting.dinneronline.client.common.YuchFlexTable;
import com.yuchting.dinneronline.client.common.YuchJSONObject;
import com.yuchting.dinneronline.client.common.YuchSimplePanel;

public class OrderOutPanel extends VerticalPanel {

	FlexTable m_currAbsSheet	= new YuchFlexTable();
	FlexTable m_currDetailSheet	= new YuchFlexTable();
	
	FlexTable m_checkAbsSheet	= new YuchFlexTable();
	FlexTable m_checkDetailSheet= new YuchFlexTable();
	
	public OrderOutPanel(MainPanel _mainPanel){
		
		VerticalPanel t_currOrderOut = new YuchSimplePanel();
		t_currOrderOut.setSpacing(5);
		t_currOrderOut.setWidth(CommonDialog.getElementWidth(_mainPanel.getElement()));
		
		Button t_refreshBtn = new Button("刷新");
		t_currOrderOut.add(t_refreshBtn);
		t_currOrderOut.add(new HTML("当前订单总揽:"));
		t_currOrderOut.add(m_currAbsSheet);
		t_currOrderOut.add(new HTML("当前订单明细:"));
		t_currOrderOut.add(m_currDetailSheet);
		
		t_refreshBtn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				CommonDialog.PopupWaiting("正在请求……");
				requestCurrOrder();				
			}
		});
		
		add(t_currOrderOut);
		
		// check some day order panel
		//
		VerticalPanel t_checkPanel = new VerticalPanel();
		t_checkPanel.setSpacing(5);
		
		add(t_checkPanel);
		
		HorizontalPanel t_timePanel = new HorizontalPanel();
		t_timePanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		t_timePanel.add(new HTML("选择日期："));
		
		final DateBox t_dateBox = new DateBox();
		t_dateBox.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("yyyy MM-dd")));
		
		t_timePanel.add(t_dateBox);
		
		Button t_checkBtn = new Button("查询");
		t_timePanel.add(t_checkBtn);
		
		t_checkPanel.add(t_timePanel);
		t_checkPanel.add(new HTML("查询菜单总揽："));
		t_checkPanel.add(m_checkAbsSheet);
		t_checkPanel.add(new HTML("查询菜单总揽："));
		t_checkPanel.add(m_checkDetailSheet);
		
		t_checkBtn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				long t_time = 0;
				if(t_dateBox.getValue() != null){
					t_time = t_dateBox.getValue().getTime();
				}else{
					CommonDialog.PopupPrompt("请选择要查询的日期", t_dateBox);
					return;
				}
				
				try{
					
					CommonDialog.PopupWaiting("正在请求……");
					
					MainPage.fsm_server.checkOrderOutList(t_time,new AsyncCallback<String>() {
						
						@Override
						public void onSuccess(String result) {
							CommonDialog.HideWaiting();
							
							if(result.startsWith("<Error>")){
								CommonDialog.PopupPrompt(result, OrderOutPanel.this);
								return ;
							}
							
							try{
								refreshListImpl(result,m_checkAbsSheet,m_checkDetailSheet,false);
							}catch(Exception e){
								CommonDialog.PopupPrompt("refreshListImpl ",e, OrderOutPanel.this);
							}
							
						}
						
						@Override
						public void onFailure(Throwable caught) {
							CommonDialog.HideWaiting();
							CommonDialog.PopupPrompt(caught.getMessage(), OrderOutPanel.this);
						}
					});
				}catch(Exception e){
					CommonDialog.HideWaiting();
					CommonDialog.PopupPrompt("exception ",e, OrderOutPanel.this);
				}
			}
		});
	}
	
	public void requestCurrOrder(){
		
		try{
			MainPage.fsm_server.getCurrOrderOutList(new AsyncCallback<String>() {
				
				@Override
				public void onSuccess(String result) {
					
					CommonDialog.HideWaiting();
					
					if(result.startsWith("<Error>")){
						CommonDialog.PopupPrompt(result, OrderOutPanel.this);
						return ;
					}
					
					try{
						refreshListImpl(result,m_currAbsSheet,m_currDetailSheet,true);
					}catch(Exception e){
						CommonDialog.PopupPrompt("refreshListImpl ",e, OrderOutPanel.this);
					}					
				}
				
				@Override
				public void onFailure(Throwable caught) {
					CommonDialog.HideWaiting();
					CommonDialog.PopupPrompt(caught.getMessage(), OrderOutPanel.this);
				}
			});
		}catch(Exception e){
			CommonDialog.HideWaiting();
			CommonDialog.PopupPrompt("exception ",e, OrderOutPanel.this);
		}
	}
		
	static final DateTimeFormat fsm_orderTimeFormat = DateTimeFormat.getFormat("yyyy MM-dd HH:mm");
	static final Date			fsm_dateTime = new Date();
	
	private void refreshListImpl(String _json,FlexTable _absTable,FlexTable _detailTable,boolean _delete)throws Exception{
		
		List<Order>	t_dataList = new ArrayList<Order>();
		
		YuchJSONObject t_list = new YuchJSONObject(_json);
		int num = t_list.m_jsonArray.size();
		for(int i = 0;i < num;i++){
			Order t_order = new Order();
			t_order.fromJSON(new YuchJSONObject((JSONObject)t_list.m_jsonArray.get(i)));
			
			t_dataList.add(t_order);
		}
		
		_absTable.removeAllRows();
		_detailTable.removeAllRows();
		
		
		// detail sheet
		//
		int t_column = 0;
		
		_detailTable.setHTML(0,t_column++,"<b>下单人</b>");
		_detailTable.setHTML(0,t_column++,"<b>菜单名</b>");
		_detailTable.setHTML(0,t_column++,"<b>菜价</b>");
		_detailTable.setHTML(0,t_column++,"<b>时间</b>");
		_detailTable.setHTML(0,t_column++,"<b>取消操作</b>");
		
		Map<String, List<Order>> t_setList = new HashMap<String, List<Order>>(); 
		
		double t_totalFee = 0;
		int t_row = 1; 
		for(int i = 0;i < t_dataList.size();i++){
			
			final Order o = t_dataList.get(i);
			
			t_column = 0;
			
			_detailTable.setHTML(t_row,t_column++,o.getUserName());
			_detailTable.setHTML(t_row,t_column++,o.getDinnerName());
			_detailTable.setHTML(t_row,t_column++,"￥" + o.getPayMoney());
			
			fsm_dateTime.setTime(o.getTime());
			_detailTable.setHTML(t_row,t_column++,fsm_orderTimeFormat.format(fsm_dateTime));
			
			if(_delete){

				final Button t_delBtn = new Button("取消订单");
				t_delBtn.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						CommonDialog.PopupYesNoDlg("你是否要删除[" + o.getUserName() + "] 的 [" + o.getDinnerName() + "] 订单么？", new YesNoHandler() {
							
							@Override
							public void Process() {
								deleteOrder(o,t_delBtn);							
							}
						},null);				
					}
				});
				
				_detailTable.setWidget(t_row,t_column++,t_delBtn);
			}			
			
			t_row++;
			
			List<Order> t_sameOrder = t_setList.get(o.getDinnerName());
			if(t_sameOrder == null){
				t_sameOrder = new ArrayList<Order>();
				t_setList.put(o.getDinnerName(),t_sameOrder);	
			}
			
			t_sameOrder.add(o);
			
			t_totalFee += o.getPayMoney();			
		}
		
		// abstract table
		//
		t_column = 0;
		_absTable.setHTML(0,t_column++,"<b>菜单名</b>");
		_absTable.setHTML(0,t_column++,"<b>份数</b>");
		_absTable.setHTML(0,t_column++,"<b>合计</b>");
		
		List<Map.Entry<String,List<Order>>> t_arrayList = new ArrayList<Map.Entry<String,List<Order>>>(t_setList.entrySet());
		t_row = 1;
		
		double t_price			= 0;
		Order	t_order			= null;
		double t_totalPrice		= 0;
		int		t_num			= 0;
		
		List<Order> t_orderList	= null;
		
		for(Map.Entry<String,List<Order>> en:t_arrayList){
			t_column = 0;
			t_orderList = en.getValue();
			_absTable.setHTML(t_row,t_column++,en.getKey());
			_absTable.setHTML(t_row,t_column++,Integer.toString(t_orderList.size()));
			
			t_order = t_orderList.get(0);
			t_price = t_order.getPayMoney() * t_orderList.size();
			_absTable.setHTML(t_row,t_column++,"￥" + t_price + " (￥" + t_order.getPayMoney() + "×" + t_orderList.size() + ")");
			
			t_totalPrice += t_price;			
			t_row++;
			t_num += t_orderList.size();
		}
		
		t_column = 0;

		_absTable.setHTML(t_row,t_column++,"<b>总计</b>");
		_absTable.setHTML(t_row,t_column++,"<b>" + t_num + "</b>");
		_absTable.setHTML(t_row,t_column++,"<b>￥" + t_totalPrice + "</b>");
	}
	
	private void deleteOrder(final Order _order,final Button _delBtn){
		_delBtn.setEnabled(false);
		
		try{
			
			MainPage.fsm_server.delOrder(_order.getUserName(), _order.getTime(),new AsyncCallback<String>(){
				
				public void onFailure(Throwable caught) {
					CommonDialog.PopupPrompt("删除菜单信息失败：" + caught.getMessage(), null);
					_delBtn.setEnabled(true);
				}

				public void onSuccess(String result) {
					
					_delBtn.setEnabled(true);
					
					if(result.startsWith("<Error>")){
						CommonDialog.PopupPrompt(result, null);
						return ;
					}
					
					CommonDialog.PopupWaiting("正在重新请求……");
					requestCurrOrder();
					
				}
			});
			
		}catch(Exception e){
			CommonDialog.PopupPrompt("删除菜单信息异常："+e.getMessage(), null);
			_delBtn.setEnabled(true);
		}
	}
}
